package com.mumu.muPictureBackend.api.aliyunai;


import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.mumu.muPictureBackend.api.aliyunai.model.CreateOutPaintingTaskRequest;
import com.mumu.muPictureBackend.api.aliyunai.model.CreateOutPaintingTaskResponse;
import com.mumu.muPictureBackend.exception.BusinessException;
import com.mumu.muPictureBackend.exception.ErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;


@Slf4j
@Component
public class AliYunAiApi {
    //读取配置文件 将key读取过来
    @Value("${aliYunAi.apiKey}")
    private String apiKey;
    //创建扩图任务的API地址 给ai发送扩图的post请求 需要携带 CreateOutPaintingTaskRequest 类型的JSON数据
    public static final String CREATE_OUT_PAINTING_TASK_URL = "https://dashscope.aliyuncs.com/api/v1/services/aigc/image2image/out-painting";
    //查询阔图任务状态的API地址 %s是占位符 用于查看某个扩图任务的执行状态和结果
    public static final String GET_OUT_PAINTING_TASK_URL = "https://dashscope.aliyuncs.com/api/v1/tasks/%s";

    //发过来请求参数用request接收 处理之后用response返回
    public CreateOutPaintingTaskResponse createOutPaintingTask(CreateOutPaintingTaskRequest createOutPaintingTaskRequest) {
        //构造请求参数 然后返回response 响应数据
        HttpRequest httpRequest = HttpRequest.post(CREATE_OUT_PAINTING_TASK_URL)
                .header("Authorization", "Bearer " + apiKey)
                // 必须开启异步处理
                .header("X-DashScope-Async", "enable")
                .header("Content-Type", "application/json")
                .body(JSONUtil.toJsonStr(createOutPaintingTaskRequest));

        try (HttpResponse httpResponse = httpRequest.execute()) {
            //如果响应失败
            if (!httpResponse.isOk()) {
                log.error("请求异常 {}", httpResponse.body());
                throw new BusinessException(ErrorCode.OPERATION_ERROR);
            }
            CreateOutPaintingTaskResponse createOutPaintingTaskResponse = JSONUtil.toBean(httpResponse.body(), CreateOutPaintingTaskResponse.class);
            if (createOutPaintingTaskResponse.getCode()==null) {
                log.error("请求异常 {}", createOutPaintingTaskRequest);
                throw new BusinessException(ErrorCode.OPERATION_ERROR);
            }
            return createOutPaintingTaskResponse;
        }

    }

}
